
package com.ikamobile.flickrer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Random;

public class PhotoHelper {

    protected static final String LOG_TAG = PhotoHelper.class.getSimpleName();

    public void loadOrSetImage(final ImageView image, final String photoUrl,
            final ProgressBar progressBar) {
        image.setTag(photoUrl);
        new AsyncTask<Void, Void, Bitmap>() {
            protected void onPreExecute() {
                if (progressBar != null)
                    progressBar.setVisibility(View.VISIBLE);
            };

            @Override
            protected Bitmap doInBackground(Void... params) {
                try {
                    File path = getPhotoPath(photoUrl);
                    if (path.exists())
                        return BitmapFactory.decodeStream(new FileInputStream(path));
                    else
                        return downloadPhoto(photoUrl);
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Failed to download photo:" + photoUrl, e);
                }
                return null;
            }

            protected void onPostExecute(Bitmap bm) {
                if (progressBar != null)
                    progressBar.setVisibility(View.GONE);
                if (bm != null && photoUrl.equals(image.getTag())) {
                    image.setImageBitmap(bm);
                }
            };

        }.execute();
    }

    public Bitmap downloadPhoto(String url) throws IOException {
        InputStream is = new URL(url).openStream();
        File path = getPhotoPath(url);
        saveToFile(is, path);
        return BitmapFactory.decodeStream(new FileInputStream(path));
    }

    private File getPhotoPath(String url) {
        String filename = url2FileName(url);
        File path = new File(getCacheDir(), filename);
        return path;
    }

    private Context mContext;
    private Random mRandom;

    public PhotoHelper(Context context) {
        mContext = context;
        mRandom = new Random();
    }

    public File getCacheDir() {
        File cacheDir = mContext.getCacheDir();
        File dir = new File(cacheDir, "flickrer-photos");
        if (!dir.exists())
            dir.mkdirs();
        return dir;
    }

    public Bitmap loadBitmap(String url) throws FileNotFoundException {
        File path = getPhotoPath(url);
        return BitmapFactory.decodeStream(new FileInputStream(path));
    }

    private String url2FileName(String url) {
        if (url != null && url.trim().length() > 0) {
            return url.replaceAll("\\/|\\:|@|\\?|&|=", "_");
        } else
            return null;
    }

    private void saveToFile(InputStream is, File path) throws IOException {
        FileOutputStream writer = null;
        try {
            writer = new FileOutputStream(path);
            byte[] buffer = new byte[1024];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) >= 0) {
                writer.write(buffer, 0, byteCount);
            }
            writer.flush();
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    public Bitmap loadRandomCachedPhoto() throws FileNotFoundException {
        File dir = getCacheDir();
        File[] files = dir.listFiles();
        if (files.length == 0)
            return null;
        else {
            File file = files[mRandom.nextInt(files.length)];
            return BitmapFactory.decodeStream(new FileInputStream(file));
        }
    }

}
